package com.shsoft.util;

import com.shsoft.MonitorApplication;
import com.shsoft.config.PCStatusConstant;
import javafx.scene.text.Font;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class FileUtil {


    public static void updateKey(String key,String newVal) throws Exception {
        InputStreamReader reader = new InputStreamReader(new FileInputStream(MonitorApplication.projectPath + "\\config\\config.properties"), "UTF-8");
        Properties prop = new Properties();
        prop.load(reader);
        reader.close();
        prop.setProperty(key, newVal);
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(MonitorApplication.projectPath + "\\config\\config.properties"), "UTF-8");
        prop.store(writer, "Updated property");
        writer.close();
    }


    public static void updateWeatherConfigs(String key, String cityName, String cityID) throws Exception {
        InputStreamReader reader = new InputStreamReader(new FileInputStream(MonitorApplication.projectPath + "\\config\\config.properties"), "utf-8");
        Properties prop = new Properties();
        prop.load(reader);
        reader.close();
        prop.setProperty("key", key);
        prop.setProperty("cityName", cityName);
        prop.setProperty("cityID", cityID);
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(MonitorApplication.projectPath + "\\config\\config.properties"), "utf-8");
        prop.store(writer, "Updated property");
        writer.close();
    }


    public static List<String> getTemplateNames(){
        List<String> list = new ArrayList<>();
        String path = MonitorApplication.projectPath + "\\data\\templates";
        File file = new File(path);
        if(file.exists()){
            File[] files = file.listFiles();
            if(files != null){
                for(File f : files){
                    if(f.isDirectory()){
                        list.add(f.getName());
                    }
                }
            }
        }
        return list;
    }


    public static String getTemplatePath(String name){
        return MonitorApplication.projectPath + "\\data\\templates\\" + name;
    }


    public static String getTemplateBackImage(String name){
        return MonitorApplication.projectPath + "\\data\\templates\\" + name + "/back.png";
    }


    public static void copyBackImage(String name) throws IOException {
        File SourceBackImage = new File(getTemplateBackImage(name));
        File targetBackImage = new File(getTmpBackImagePath());
        if(SourceBackImage.exists()){
            Files.copy(SourceBackImage.toPath(), targetBackImage.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
    }


    public static String getTmpBackImagePath(){
        return MonitorApplication.projectPath + "\\data\\image\\tmpBack.png";
    }


    public static String getTemplateTotalImage(String name){
        return MonitorApplication.projectPath + "\\data\\templates\\" + name + "/total.png";
    }


    public static String getTemplateComponents(String name){
        return MonitorApplication.projectPath + "\\data\\templates\\" + name + "/components.ser";
    }


    public static List<String> getFontList(){
        List<String> list = new ArrayList<>();
        String path = MonitorApplication.projectPath + "\\data\\font";
        File dir = new File(path);
        if(dir.exists()){
            File[] files = dir.listFiles();
            for (File file : files) {
                String name = file.getName();
                if(name.endsWith(".ttf") && !name.equals("iconfont.ttf")){
                    list.add(name.replace(".ttf", ""));
                }
                if(name.endsWith(".otf")){
                    list.add(name.replace(".otf", ""));
                }
            }
        }
        return list;
    }


    public static Font getFont(String fontName, int fontSize){
        Font font = MonitorApplication.mainController.fontMap.get(fontName + fontSize);
        if(font == null){
            FileInputStream inputStream = FileUtil.getFontInputStream(fontName);
            font = Font.loadFont(inputStream, fontSize);
            MonitorApplication.mainController.fontMap.put(fontName + fontSize, font);
        }
        return font;
    }


    private static FileInputStream getFontInputStream(String fontName){
        try {
            String path;
            if(fontName.equals("思源宋体")){
                path = URLDecoder.decode(MonitorApplication.projectPath + "\\data\\font\\"  + fontName + ".otf", "utf-8");
            }else {
                path = URLDecoder.decode(MonitorApplication.projectPath + "\\data\\font\\"  + fontName + ".ttf", "utf-8");
            }
            File file = new File(path);
            return new FileInputStream(file);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static boolean deleteDir(File dir){
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            if(files != null){
                for(File f : files){
                     deleteDir(f);
                }
            }
        }
        return dir.delete();
    }


    public static String copyImage(String srcPath,String targetDir){
        File srcFile = new File(srcPath);
        File targetFile = new File(targetDir + "/" + srcFile.getName());
        try {
            InputStream in = new FileInputStream(srcFile);
            OutputStream out = new FileOutputStream(targetFile);
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len=in.read(bytes))!=-1) {
                out.write(bytes, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return srcFile.getName();
    }


    public static String getImagePath(String templateName, String imageName){
        return MonitorApplication.projectPath + "\\data\\templates\\" + templateName + "/images/" + imageName;
    }


    public static String getAnimPath(String templateName, String imageName){
        return MonitorApplication.projectPath + "\\data\\templates\\" + templateName + "/anim/" + imageName;
    }


    public static byte[] getRGB565ByteArray(BufferedImage image, int x, int y){
        int width = image.getWidth();
        int height = image.getHeight();
        byte[] pixels = new byte[width * height * 2 + 15];
        pixels[0] = (byte) 255;
        pixels[1] = 12;
        pixels[2] = 34;
        pixels[3] = PCStatusConstant.MSG_DATA;
        pixels[4] = (byte) (width / 256);
        pixels[5] = (byte) (width % 256);
        pixels[6] = (byte) (height / 256);
        pixels[7] = (byte) (height % 256);
        pixels[8] = (byte) (x / 256);
        pixels[9] = (byte) (x % 256);
        pixels[10] = (byte) (y / 256);
        pixels[11] = (byte) (y % 256);
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                int rgb = image.getRGB(col, row);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                short rgb565 = (short) ((r & 0xF8) << 8 | (g & 0xFC) << 3 | (b & 0xF8) >> 3);
                pixels[12 + (row * width + col) * 2] = (byte) ((rgb565 >> 8) & 0xFF);
                pixels[12 + (row * width + col) * 2 + 1] = (byte) (rgb565 & 0xFF);
            }
        }
        pixels[pixels.length - 3] = 43;
        pixels[pixels.length - 2] = 21;
        pixels[pixels.length - 1] = (byte) 255;
        return pixels;
    }


    public static byte[] getAnimMsg(){
        return new byte[]{(byte)255,12,34,PCStatusConstant.MSG_ANIM_OPTIONS,0,0,0,0,0,0,0,0,0,0,0,43,21,(byte)255};
    }


    public static byte[] getAnimByteArray(BufferedImage image, int frameNum){
        int width = image.getWidth();
        int height = image.getHeight();
        byte[] pixels = new byte[width * height * 2 + 8];
        pixels[0] = (byte) 255;
        pixels[1] = 12;
        pixels[2] = 34;
        pixels[3] = PCStatusConstant.MSG_ANIM_FRAME;
        pixels[4] = (byte) frameNum;
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                int rgb = image.getRGB(col, row);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                short rgb565 = (short) ((r & 0xF8) << 8 | (g & 0xFC) << 3 | (b & 0xF8) >> 3);
                pixels[5 + (row * width + col) * 2] = (byte) ((rgb565 >> 8) & 0xFF);
                pixels[5 + (row * width + col) * 2 + 1] = (byte) (rgb565 & 0xFF);
            }
        }
        pixels[pixels.length - 3] = 43;
        pixels[pixels.length - 2] = 21;
        pixels[pixels.length - 1] = (byte) 255;
        return pixels;
    }


    public static void doBackImageArrays(BufferedImage image){
        List<byte[]> bytesList = new ArrayList<>();
        for(int i = 0; i < 8; i++){
            byte[] pixels = new byte[PCStatusConstant.BACK_IMAGE_PART_SIZE];
            pixels[0] = (byte) 255;
            pixels[1] = 12;
            pixels[2] = 34;
            pixels[3] = PCStatusConstant.MSG_BACK;
            pixels[4] = (byte) (i + 1);
            for(int row = 0; row < 40; row++){
                for (int col = 0; col < 480; col++) {
                    int rgb = image.getRGB(col, row + (i * 40));
                    int r = (rgb >> 16) & 0xFF;
                    int g = (rgb >> 8) & 0xFF;
                    int b = rgb & 0xFF;
                    // 将RGB信息转换为RGB565格式
                    short rgb565 = (short) ((r & 0xF8) << 8 | (g & 0xFC) << 3 | (b & 0xF8) >> 3);
                    // 存储到数组中
                    pixels[5 + (row * 480 + col) * 2] = (byte) ((rgb565 >> 8) & 0xFF);
                    pixels[5 + (row * 480 + col) * 2 + 1] = (byte) (rgb565 & 0xFF);
                }
            }
            pixels[pixels.length - 3] = 43;
            pixels[pixels.length - 2] = 21;
            pixels[pixels.length - 1] = (byte) 255;
            bytesList.add(pixels);
        }
        for (byte[] bytes : bytesList) {
            MonitorApplication.priorityDataArray.offer(bytes);
        }
    }

}
